package com.wei.web.interceptor;

import com.wei.annotation.AuthorityVerify;
import com.wei.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CrossOriginHandler implements HandlerInterceptor {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return;
        }
        HandlerMethod handlerMethod = ((HandlerMethod) handler);
        CrossOrigin crossOrigin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(CrossOrigin.class);
        if (crossOrigin == null) {
            crossOrigin = handlerMethod.getMethodAnnotation(CrossOrigin.class);
        }
        if (crossOrigin == null) {
            return;
        }
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
}
